package com.tdtxdcxm.ruralcommunity.slice;

import com.tdtxdcxm.ruralcommunity.ResourceTable;
import com.tdtxdcxm.ruralcommunity.appruntime.DataCenterControl;
import com.tdtxdcxm.ruralcommunity.httpmanagers.ThreadPoolUtil;
import com.tdtxdcxm.ruralcommunity.items.LCArryListNormalItem;
import com.tdtxdcxm.ruralcommunity.myutils.MyTools;
import com.tdtxdcxm.ruralcommunity.providers.LCProviderForNormal;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;
import ohos.utils.zson.ZSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class FollowAndFansListSlice extends AbilitySlice {
    private Button usercontent_backbut;
    private ListContainer usercontent_lc;


    /*<****************http下载用户关注和粉丝列表据区域*****************/
    public void DownDataFollowAndFanslistInfo(String username,String type){
        NetManager main_toplistnetmanger = NetManager.getInstance(this.getContext());
        if (!main_toplistnetmanger.hasDefaultNet()) {
            return;
        }
        ThreadPoolUtil.submit(() -> {
            NetHandle thenetHandle = main_toplistnetmanger.getDefaultNet();
            NetStatusCallback netStatusCallback = new NetStatusCallback() {};
            HttpURLConnection httpURLConnection = null;
            String urlString = null;
            switch (type) {
                case "followlist":

                    urlString = DataCenterControl.serverIpWithPort + "followlist/?";
                    break;
                case "fanslist":

                    urlString = DataCenterControl.serverIpWithPort + "fanslist/?";
                    break;
                default:

                    urlString = DataCenterControl.serverIpWithPort + "inedx/?";
                    break;
            }

            try {
                URL url = new URL(urlString);

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                URLConnection urlConnection = thenetHandle.openConnection(url, java.net.Proxy.NO_PROXY);
                if (urlConnection instanceof HttpURLConnection) {
                    httpURLConnection = (HttpURLConnection) urlConnection;

                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);

                    StringBuilder stringBuilder = new StringBuilder();

                    stringBuilder.append("username=");
                    stringBuilder.append(username);

                    byte[] b = stringBuilder.toString().getBytes();
                    httpURLConnection.getOutputStream().write(b);

                    try {
                        httpURLConnection.connect();
                    } catch (IOException e) {}
                    outputStream.flush();


                    InputStream inputStream = null;
                    try {
                        inputStream = urlConnection.getInputStream();
                        byte[] cache = new byte[2 * 1024];
                        int len = inputStream.read(cache);
                        while (len != -1) {
                            outputStream.write(cache, 0, len);
                            len = inputStream.read(cache);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = "";
                    result = outputStream.toString();

                    if(result.indexOf("sum") != -1){
                        //搜索成功
                        String finalResult = result;
                        switch (type){
                            case "followlist":
                                DataCenterControl.follow_listcontainer_list.clear();
                                ZSONObject zsonobject_follow = ZSONObject.stringToZSON(finalResult);
                                int sum_follow = Integer.parseInt(zsonobject_follow.getString("sum"));
                                for(int i = 0;i < sum_follow;i++){
                                    String info = zsonobject_follow.getString(String.valueOf(i));
                                    DataCenterControl.follow_listcontainer_list.add(new LCArryListNormalItem(info));
                                }
                                getUITaskDispatcher().asyncDispatch(new Runnable() {
                                    @Override
                                    public void run() {
                                        if(DataCenterControl.followAndFanaListListContainerProvider != null){
                                            DataCenterControl.followAndFanaListListContainerProvider.notifyDataChanged();
                                        }
                                        MyTools.toastShow("关注列表下载成功！", FollowAndFansListSlice.this.getContext());
                                    }
                                });
                                break;
                            case "fanslist":
                                DataCenterControl.fans_listcontainer_list.clear();
                                ZSONObject zsonobject_fans = ZSONObject.stringToZSON(finalResult);
                                int sum_fans = Integer.parseInt(zsonobject_fans.getString("sum"));
                                for(int i = 0;i < sum_fans;i++){
                                    String info = zsonobject_fans.getString(String.valueOf(i));
                                    DataCenterControl.fans_listcontainer_list.add(new LCArryListNormalItem(info));
                                }
                                getUITaskDispatcher().asyncDispatch(new Runnable() {
                                    @Override
                                    public void run() {
                                        if(DataCenterControl.followAndFanaListListContainerProvider != null){
                                            DataCenterControl.followAndFanaListListContainerProvider.notifyDataChanged();
                                        }
                                        MyTools.toastShow("粉丝列表下载成功！", FollowAndFansListSlice.this.getContext());
                                    }
                                });
                                break;
                            default:
                                break;
                        }
                    }
                    else{
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                MyTools.toastShow("好友为空！", FollowAndFansListSlice.this.getContext());
                            }
                        });
                    }
                }
            } catch (IOException e) {

            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
        });
    }
    /******************http下载用户关注和粉丝列表据区域***************>*/

    /*<****************http发送关注或取消关注指令区域*****************/
    public void UpDataFollowInfo(String user_id,int i,String operation){
        NetManager main_toplistnetmanger = NetManager.getInstance(this.getContext());
        if (!main_toplistnetmanger.hasDefaultNet()) {
            return;
        }
        ThreadPoolUtil.submit(() -> {
            NetHandle thenetHandle = main_toplistnetmanger.getDefaultNet();
            NetStatusCallback netStatusCallback = new NetStatusCallback() {};
            HttpURLConnection httpURLConnection = null;
            String urlString = "";
            if(operation.equals("关注")){

                urlString = DataCenterControl.serverIpWithPort + "follow/?";
            }
            if(operation.equals("取消关注")){

                urlString = DataCenterControl.serverIpWithPort + "unfollow/?";
            }

            try {
                URL url = new URL(urlString);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                URLConnection urlConnection = thenetHandle.openConnection(url, java.net.Proxy.NO_PROXY);
                if (urlConnection instanceof HttpURLConnection) {
                    httpURLConnection = (HttpURLConnection) urlConnection;
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);

                    StringBuilder stringBuilder = new StringBuilder();

                    stringBuilder.append("username=");
                    stringBuilder.append(DataCenterControl.userName);

                    stringBuilder.append("&user_id=");
                    stringBuilder.append(user_id);


                    byte[] b = stringBuilder.toString().getBytes();
                    httpURLConnection.getOutputStream().write(b);
                    try {
                        httpURLConnection.connect();
                    } catch (IOException e) {}
                    outputStream.flush();

                    InputStream inputStream = null;
                    try {
                        inputStream = urlConnection.getInputStream();
                        byte[] cache = new byte[2 * 1024];
                        int len = inputStream.read(cache);
                        while (len != -1) {
                            outputStream.write(cache, 0, len);
                            len = inputStream.read(cache);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = "";
                    result = outputStream.toString();

                    String[] tosettext = {"","",""};
                    if(result.equals("OK")){
                        if(operation.equals("关注")){}
                        if(operation.equals("取消关注")){
                            getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    DataCenterControl.follow_listcontainer_list.remove(i);
                                    DataCenterControl.followAndFanaListListContainerProvider.notifyDataChanged();
                                    MyTools.toastShow("已取消关注",FollowAndFansListSlice.this.getContext());
                                }
                            });
                        }
                    }
                }
            } catch (IOException e) {

            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
        });
    }
    /******************http发送关注或取消关注指令区域***************>*/

    private void initListContainer(ListContainer listContainer,String listContainerName,AbilitySlice slice){
        if(listContainer == null){
            return;
        }
        listContainer.setName(listContainerName);
        LCProviderForNormal lcProviderForNormal = null;
        switch (listContainerName) {
            case "followlistlc":
                lcProviderForNormal = new LCProviderForNormal(DataCenterControl.follow_listcontainer_list,this);
                break;
            case "fanslistlc":
                lcProviderForNormal = new LCProviderForNormal(DataCenterControl.fans_listcontainer_list,this);
                break;
            default:
                break;
        }

        if(lcProviderForNormal != null){
            listContainer.setItemProvider(lcProviderForNormal);
            DataCenterControl.followAndFanaListListContainerProvider = lcProviderForNormal;
        }

        listContainer.setItemLongClickedListener(new ListContainer.ItemLongClickedListener() {
            @Override
            public boolean onItemLongClicked(ListContainer listContainer, Component component, int i, long l) {
                DirectionalLayout directionalLayout= ((DirectionalLayout)component);
                Text text = (Text)directionalLayout.getComponentAt(0);


                if(listContainer.getName().equals("followlistlc")){
                    MyTools.commonDialogRemoveShow("取消关注提示","是否取消关注？",component,i,FollowAndFansListSlice.this,"unfollow");
                }
                return true;
            }
        });
    }

    private void initPLSComponents(){
        usercontent_backbut = (Button) findComponentById(ResourceTable.Id_usercontent_backbut);
        usercontent_lc = (ListContainer) findComponentById(ResourceTable.Id_usercontent_lc);

        usercontent_backbut.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                DataCenterControl.follow_listcontainer_list.clear();
                DataCenterControl.fans_listcontainer_list.clear();
                terminate();
            }
        });
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_usercontent_item_listcontainer);
        initPLSComponents();
        String type = intent.getStringParam("type");
        switch (type) {
            case "followlist":
                initListContainer(usercontent_lc,"followlistlc",this);
                DownDataFollowAndFanslistInfo(DataCenterControl.userName,"followlist");
                break;
            case "fanslist":
                initListContainer(usercontent_lc,"fanslistlc",this);
                DownDataFollowAndFanslistInfo(DataCenterControl.userName,"fanslist");
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
